package com.zl.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.exceptions.ExceptionUtil;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

/**
 * 提供一个简单的模板工具类，方便内部使用
 * @author zhouliang
 *
 */
public class FreemarkerTool {
    private static final Logger LOGGER = LoggerFactory.getLogger(FreemarkerTool.class);
    
    public static void setConfiguration(Configuration cfg)  {
        cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_30));
        cfg.setEncoding(Locale.getDefault(), "UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLocale(Locale.CHINA);
    }
    
    // 加载模板目录，绝对文件路径或classpath
    public static Configuration initFreemarker(String dir) {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
        setConfiguration(cfg);
        if(StringUtils.isBlank(dir)) {
            return cfg;
        }
        if(dir.startsWith("classpath:")) {
             cfg.setClassForTemplateLoading(FreemarkerTool.class, dir.replace("classpath:",""));
        }else {
             try {
                cfg.setDirectoryForTemplateLoading(new File(dir));
             } catch (IOException e) {
                LOGGER.info("加载文件路径错误>>{}",dir);
             } 
        }
        return cfg;
    }
    
    /** 生成文件*/
    public static String processFile(Configuration cfg,Object rootMap, String templateName, String outputName,boolean appendFlag) {
        return processFile(cfg, rootMap, "UTF-8", templateName, outputName, appendFlag);
    }
    public static String processFile(Configuration cfg,Object rootMap, String enc, String templateName, String outputName,boolean appendFlag) {
        Writer out = null;
        try {
            Template tpl = cfg.getTemplate(templateName, enc);
            File tf = new File(outputName);
            File pf = tf.getParentFile();
            pf.mkdirs();
            out = new OutputStreamWriter(new FileOutputStream(tf,appendFlag), enc);
            tpl.process(rootMap, out);
            out.flush();
        } catch (Exception e) {
            LOGGER.error("文件生成异常>>{}", e);
            return ExceptionUtil.getSimpleMessage(e);
        } finally {
            IOUtils.closeQuietly(out);
        }
        return null;
    }
    
    /**
     * 生成 String
     */
    public static String processString(Configuration cfg,Object params,String templateName) {
       return processString(cfg, params, templateName, "UTF-8");
    }
    public static String processString(Configuration cfg,Object params,String templateName, String enc) {
        try {
            Template template = cfg.getTemplate(templateName, enc);
            StringWriter result = new StringWriter();
            template.process(params, result);
            return result.toString();
        } catch (Exception e) {
            LOGGER.error("文件生成异常>>{}", e);
        }
        return null;
    }

}
